package com.yinhai.message.implement.dwr.util;

import com.alibaba.fastjson.JSON;
import com.yinhai.core.common.api.config.impl.SysConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by yanglq on 2018/3/19 0019.
 */
public class RedisTool {
    private static JedisCluster jedisCluster = null;
    private static RedisTool redisTool = null;

    public synchronized static RedisTool getInstance() throws Exception{
        if(redisTool==null){
            redisTool = new RedisTool();
            String redisString = SysConfig.getSysConfig("redisAddress","localhost:6379");
            String[] hostArray = redisString.split(",");
            Set<HostAndPort> nodes = new HashSet<>();
            //配置redis集群
            for(String host : hostArray)
            {
                String[] detail = host.split(":");
                nodes.add( new HostAndPort(detail[0] , Integer.parseInt(detail[1])) );
            }
            jedisCluster = new JedisCluster(nodes);
        }
        return redisTool;
    }

    public void userOnLine(String systemid,String userid,String online){
        if("on".equals(online)){
            jedisCluster.setex(systemid+userid+"_on",3000,"on");
        }else{
            jedisCluster.del(systemid+userid);
        }
    }

    public void setMessage(String mgid,String systemid,String userid,Object message){
        if("on".equals(jedisCluster.get(systemid+userid+"_on")))
            jedisCluster.hset(systemid+userid,mgid,JSON.toJSONString(message));
    }

    public Map<String,String> getMessage(String systemid,String userid){
        Map<String,String> map = jedisCluster.hgetAll(systemid+userid);
        jedisCluster.del(systemid+userid);
        return map;
    }

    public JedisCluster getJedisCluster(){
        return jedisCluster;
    }
}
